
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;

using Swaf;
using Swaf.BizObj;
using Swaf.BizRule;
using Swaf.Container;
using Swaf.Security;

using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Core;

namespace eCom
{
	public class eComBackupBizRules : Syrinx.BaseBizRules
	{
		public void backupCompanyProducts(IApplication app, IRuleContext context, string treeName, IBizObj deployInfo, ZipOutputStream zOut)
		{
			if (deployInfo == null)
				throw new eComException("required parameter is missing. error executing backupCompanyProducts bizrule.");

			Dictionary<string, int> articleTitles = new Dictionary<string, int>();
			Debug.Assert(zOut != null);
			//We need to change the active company id to the company that the backup is for so that
			//any reference to the activeCompanyId in the following company will point to the correct company.
			Swaf.BGuid.Guid oldCmpId = ActiveCompanyId;
			try
			{
				foreach (IBizObj company in deployInfo.get("backupCompanies") as IBizObjList)
				{
					ActiveCompanyId = company.get("id") as Swaf.BGuid.Guid;
					FlexiMap info = new FlexiMap();
					info.put("companyId", company.get("id") as Swaf.BGuid.Guid);
					info.put("includeSelf", true);
					info.put("listDetailLevel", DetailLevel.fullDetails);
					info.put("includeTranslations", true);
					info.put("defaultCacheName", company.get("settings.defaultMediaCache"));

					IResults rc = app.ruleMgr.execute("getProducts", info, (IBizObj)null);
					IBizObjList books = rc.CallResults as IBizObjList;

					//process each book as xml
					if (books != null)
						foreach (IBizObj book in books)
						{
							info.put("parentId", book.get("id"));
							info.put("entireTree", true);
							rc = app.ruleMgr.execute("getProducts", info, (IBizObj)null);
							IBizObjList fullBook = rc.CallResults as IBizObjList;
							if (fullBook != null)
							{
								string bookZipEntryName = (string)book.get("baseTitle");
								int numWithTitle = 0;
								articleTitles.TryGetValue(bookZipEntryName, out numWithTitle);
								articleTitles[bookZipEntryName] = ++numWithTitle;

								if (numWithTitle > 1)
									bookZipEntryName += "-" + numWithTitle;

								zOut.PutNextEntry(new ZipEntry(string.Format("data{0}{1}{0}Products{0}{2}.xml", Path.DirectorySeparatorChar, company.get("shortName"), bookZipEntryName)));
								TextWriter t = (TextWriter)context.get("zipWriter");
								t.Write("<?xml version=\"1.0\" ?>\n" + fullBook.Xml.ToString());
								t.Flush();
							}
						}
				}
			}
			catch (Exception e)
			{
				throw new eComException("error executing backupCompanyProducts.", e);
			}
			finally
			{
				ActiveCompanyId = oldCmpId;
			}
		}

		public void backupCheckoutWizards(IApplication app, IRuleContext context, IBizObj deployInfo, ZipOutputStream zOut)
		{
			try
			{
				foreach (IBizObj company in deployInfo.get("backupCompanies") as IBizObjList)
				{
					context.put("companyId", company.get("id"));
					IBizObjList wizSteps = app.appData.get("DA.eCom.GetPreCheckOutWizardSteps", context) as IBizObjList;
					zOut.PutNextEntry(new ZipEntry(string.Format("data{0}{1}{0}PreCheckoutWizardSteps.xml", Path.DirectorySeparatorChar, company.get("shortName"))));
					TextWriter t = (TextWriter)context.get("zipWriter");
					t.Write("<?xml version=\"1.0\" ?>\n" + wizSteps.Xml.ToString());
					t.Flush();
				}
			}
			catch (Exception e)
			{
				throw new eComException("error executing backupCheckoutWizards.", e);
			}
		}

		public void backupPaymentTerms(IApplication app, IRuleContext context, IBizObj deployInfo, ZipOutputStream zOut)
		{
			try
			{
				foreach (IBizObj company in deployInfo.get("backupCompanies") as IBizObjList)
				{
					context.put("companyId", company.get("id"));
					IResults rc = context.RuleGroup.execute(context, "getCompanyPaymentTerms", company.get("id"));
					IBizObjList payTerms = rc.CallResults as IBizObjList;
					if (payTerms != null)
					{
						zOut.PutNextEntry(new ZipEntry(string.Format("data{0}{1}{0}CompanyPaymentTerms.xml", Path.DirectorySeparatorChar, company.get("shortName"))));
						TextWriter t = (TextWriter)context.get("zipWriter");
						t.Write("<?xml version=\"1.0\" ?>\n" + payTerms.Xml.ToString());
						t.Flush();
					}

					rc = context.RuleGroup.execute(context, "getAllUsersPaymentTerms", company.get("id"));
					payTerms = rc.CallResults as IBizObjList;
					if (payTerms != null)
					{
						zOut.PutNextEntry(new ZipEntry(string.Format("data{0}{1}{0}UserPaymentTerms.xml", Path.DirectorySeparatorChar, company.get("shortName"))));
						TextWriter t = (TextWriter)context.get("zipWriter");
						t.Write("<?xml version=\"1.0\" ?>\n" + payTerms.Xml.ToString());
						t.Flush();
					}
				}
			}
			catch (Exception e)
			{
				throw new eComException("error executing backupCheckoutWizards.", e);
			}
		}

		public void backupTaxesDiscounts(IApplication app, IRuleContext context, IBizObj deployInfo, ZipOutputStream zOut)
		{
			try
			{
				foreach (IBizObj company in deployInfo.get("backupCompanies") as IBizObjList)
				{
					context.put("companyId", company.get("id"));
					IResults rc = context.RuleGroup.execute(context, "getTaxDefinitions", company.get("id"));
					IBizObjList taxes = rc.CallResults as IBizObjList;
					if (taxes != null)
					{
						zOut.PutNextEntry(new ZipEntry(string.Format("data{0}{1}{0}TaxDefinitions.xml", Path.DirectorySeparatorChar, company.get("shortName"))));
						TextWriter t = (TextWriter)context.get("zipWriter");
						t.Write("<?xml version=\"1.0\" ?>\n" + taxes.Xml.ToString());
						t.Flush();
					}
					rc = context.RuleGroup.execute(context, "getQuantityDiscounts", company.get("id"));
					IBizObjList disc = rc.CallResults as IBizObjList;
					if (disc != null)
					{
						zOut.PutNextEntry(new ZipEntry(string.Format("data{0}{1}{0}QuantityDiscounts.xml", Path.DirectorySeparatorChar, company.get("shortName"))));
						TextWriter t = (TextWriter)context.get("zipWriter");
						t.Write("<?xml version=\"1.0\" ?>\n" + disc.Xml.ToString());
						t.Flush();
					}
				}
			}
			catch (Exception e)
			{
				throw new eComException("error executing backupCheckoutWizards.", e);
			}
		}

		public void backupSalesOrders(IApplication app, IRuleContext context, IBizObj deployInfo, ZipOutputStream zOut)
		{
		}

		public void postExtendEComexecuteCompanyBackup(IApplication app, IRuleContext context, object returnValue, object[] inputParams)
		{

			try
			{
				INameAddressSupport deployInfo = inputParams[2] as INameAddressSupport;
				ZipOutputStream zOut = inputParams[3] as ZipOutputStream;
				IResults rc = null;
				bool fullBackup = (bool)deployInfo.get("fullCompanyBackup");

				if (fullBackup || (bool)deployInfo.get("backupCompanyProducts"))
					rc = context.RuleGroup.execute(context, "backupCompanyProducts", "Articles", deployInfo, zOut);
				if (fullBackup || (bool)deployInfo.get("backupCheckoutWizards"))
					rc = context.RuleGroup.execute(context, "backupCheckoutWizards", deployInfo, zOut);
				if (fullBackup || (bool)deployInfo.get("backupPaymentTerms"))
					rc = context.RuleGroup.execute(context, "backupPaymentTerms", deployInfo, zOut);
				if (fullBackup || (bool)deployInfo.get("backupTaxesDiscounts"))
					rc = context.RuleGroup.execute(context, "backupTaxesDiscounts", deployInfo, zOut);
				if (fullBackup || (bool)deployInfo.get("backupSalesOrders"))
					rc = context.RuleGroup.execute(context, "backupSalesOrders", deployInfo, zOut);
			}
			catch (Exception e)
			{
				throw new eComException("error executing postExtendEComexecuteCompanyBackup.", e);
			}
		}

	}
}
